import React from 'react'
import { Button, message, Modal} from 'antd'
import Table from '../../../components/Table'
import 'whatwg-fetch'
import API from '../../../axios/api'
import { PermissionStatus } from '../../../utils/system-data'
import { keyToValue } from '../../../utils/utils'
import ArticleModalFormsee from './formsee'
import ArticleModalForm from './form'

import FormtagModalForm from './formtag'


require('es6-promise').polyfill();

const confirm = Modal.confirm

export default class Article extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            tData: [],
            item: {},
            CategoryList:[],
            loading: true,
            modalShow: false,
            tagmodalShowEdit:false,
            Id: '',
            Page: 1,
            Pages:1,
            modalShowSee:false
        }
    }

    onPageChange = (e) =>{
        this.setState({
            Page:e,
        },()=>{
            this.fetchTableData()
        })
    }


    // 获取表格数据
    fetchTableData =  async () => {
        let parms = {
            Page:this.state.Page,
            PageSize: 10,
        }
        await API.fetchArticlePages(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    tData: res.Data.List,
                    Pages:res.Data.Pages
                });
            }
            this.setState({
                loading: false
            });
        })
    }

    componentDidMount() {
        this.fetchTableData()
        this.getCategoryList()
    }

    getCategoryList = () =>{
        let parms = {}
        API.GetArticleCategoryList(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    CategoryList: res.Data,
                });
            }
        })
    }

    add = () =>{
        this.setState({
            modalShow: true
        })
    }

    onOk = (param) =>{
        API.addArticle(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('添加成功')
                this.fetchTableData()
                this.onCancel()
            }
            else message.error(res.Message)
        })
    }

    onCancel = () =>{
        this.setState({
            modalShow: false,
            modalShowEdit:false,
            tagmodalShowEdit:false,
            modalShowSee:false
        })
    }

    onOkEdit = (param) =>{
        this.setState({
            modalShowEdit: false
        })
        // param.Id = this.state.item.Id
        API.editArticle(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('添加成功')
                this.onCancel()
                this.fetchTableData()
            }
            else message.error(res.Message)
        })
    }

    onOktagEdit = (param) =>{
        
    }

    addArticleLabel = () => {
        this.setState({
            tagmodalShowEdit:true
        })
    }

    tableAction = (actionKey, item) => {
        if (actionKey === 'edit') {
            const param = {
                Id: item.Id
            }
            API.getArticleDetail(param).then(res =>{
                if(res.Code === 200)
                {
                    let data = res.Data
                    let labelArr = []
                    let keys = []
                    let details = []
                    if(data){
                        if(item.ArticleLogo){ // 缩略图
                            const _temp =[{
                                uid: 0,
                                status: 'done',
                                url: item.ArticleLogo,
                                response: {
                                    Data: item.ArticleLogo
                                }
                            }]
                            data.ArticleLogo = _temp
                        }
                        if(item.ArticleShareImage){ // 分享图
                            const _temp =[{
                                uid: 0,
                                status: 'done',
                                url: item.ArticleShareImage,
                                response: {
                                    Data: item.ArticleShareImage
                                }
                            }]
                            data.ArticleShareImage = _temp
                        }
                        data.LabelList.map(item => {
                            // labelArr.push(item.ArticleLableName)
                            labelArr.push(item.ArticleLableId)
                        })
                        let _file = []
                        let _file3 = []

                        // let ctype = data.ArticleContentList && data.ArticleContentList.length > 0 ? data.ArticleContentList[0].ContentType : 2
                        data.ArticleContentList.map((item, index) => {
                            if (item.ContentType === 1){
                                const _index = keys && keys.length>1 ? keys.length -1 : keys.length
                                keys.push({id: _index, type: 'content'})
                                details.push({
                                    Content: item.Content
                                })
                            }
                            if(item.ContentType === 2){
                                const _index = keys && keys.length>1 ? keys.length -1 : keys.length
                                keys.push({id: _index, type: 'file'})
                                let _item = {
                                    uid: index,
                                    status: 'done',
                                    url: item.Content ,
                                    type:'image',
                                    response: {
                                        Data: item.Content
                                    }
                                }
                                _file.push(_item)
                                details.push({
                                    file: _file
                                })
                                _file = []
                            }
                            if(item.ContentType === 3){
                                const _index = keys && keys.length>1 ? keys.length -1 : keys.length
                                keys.push({id: _index, type: 'video'})
                                let _item = {
                                    uid: index,
                                    status: 'done',
                                    url: item.Content ,
                                    type:'video',
                                    response: {
                                        Data: item.Content
                                    }
                                }
                                _file3.push(_item)
                                details.push({
                                    file: _file3
                                })
                                _file3 = []
                            }
                        })
                    }
                    data.keys = keys
                    data.details = details
                    data.LabelList = labelArr
                    this.setState({
                        item: data,
                        modalShowEdit: true
                    })
                }
                else message.error(res.Message)
            })
        }else if(actionKey === 'down'){
            let that = this
            let param = {Id:item.Id}
            if(item.Status == 1){
                message.success('该文章已下架，请勿重复操作')
                return false;
            }
            confirm({
                title: '提示',
                content: '确定下架该文章吗',
                onOk: () => {
                    API.deleteArticle(param).then(res => {
                        if(res.Code === 200){
                             message.success('下架成功')
                             that.fetchTableData()
                        }else{
                            message.error(res.Message)
                        }
                    })
                  
                },
                onCancel() {}
            })
        }else if(actionKey == 'up'){
            let that = this
            let param = {Id:item.Id}
            if(item.Status == 0){
                message.success('该文章已上架架，请勿重复操作')
                return false;
            }
            API.shelfArticle(param).then(res => {
                if(res.Code === 200){
                     message.success('上架成功')
                     that.fetchTableData()
                }else{
                    message.error(res.Message)
                }
            })
        }
        else if(actionKey == 'see'){

            const param = {
                Id: item.Id
            }
            API.getArticleDetail(param).then(res =>{
                if(res.Code === 200)
                {
                    let data = res.Data
                    let labelArr = []
                    let keys = []
                    let details = []
                    if(data){
                        if(item.ArticleLogo){ // 缩略图
                            const _temp =[{
                                uid: 0,
                                status: 'done',
                                url: item.ArticleLogo,
                                response: {
                                    Data: item.ArticleLogo
                                }
                            }]
                            data.ArticleLogo = _temp
                        }
                        if(item.ArticleShareImage){ // 分享图
                            const _temp =[{
                                uid: 0,
                                status: 'done',
                                url: item.ArticleShareImage,
                                response: {
                                    Data: item.ArticleShareImage
                                }
                            }]
                            data.ArticleShareImage = _temp
                        }
                        data.LabelList.map(item => {
                            // labelArr.push(item.ArticleLableName)
                            labelArr.push(item.ArticleLableId)
                        })
                        let _file = []
                        let _file3 = []

                        // let ctype = data.ArticleContentList && data.ArticleContentList.length > 0 ? data.ArticleContentList[0].ContentType : 2
                        data.ArticleContentList.map((item, index) => {
                            if (item.ContentType === 1){
                                const _index = keys && keys.length>1 ? keys.length -1 : keys.length
                                keys.push({id: _index, type: 'content'})
                                details.push({
                                    Content: item.Content
                                })
                            }
                            if(item.ContentType === 2){
                                const _index = keys && keys.length>1 ? keys.length -1 : keys.length
                                keys.push({id: _index, type: 'file'})
                                let _item = {
                                    uid: index,
                                    status: 'done',
                                    url: item.Content ,
                                    type:'image',
                                    response: {
                                        Data: item.Content
                                    }
                                }
                                _file.push(_item)
                                details.push({
                                    file: _file
                                })
                                _file = []
                            }
                            if(item.ContentType === 3){
                                const _index = keys && keys.length>1 ? keys.length -1 : keys.length
                                keys.push({id: _index, type: 'video'})
                                let _item = {
                                    uid: index,
                                    status: 'done',
                                    url: item.Content ,
                                    type:'video',
                                    response: {
                                        Data: item.Content
                                    }
                                }
                                _file3.push(_item)
                                details.push({
                                    file: _file3
                                })
                                _file3 = []
                            }
                        })
                    }
                    data.keys = keys
                    data.details = details
                    data.LabelList = labelArr
                    this.setState({
                        item: data,
                        modalShowSee: true
                    })
                }
                else message.error(res.Message)
            })
        }
    }


    fields = () => {
        return [
            { label: '菜单名称', type: 'input', name: 'PermissionName',
                options: {
                    rules: [
                        { required: true, message: '菜单名称必填!',}
                    ]
                }
            },
            {
                label: '类型',
                type: 'select',
                name: 'PermissionType',
                defaultValue: '后台',
                items: () => PermissionStatus,
                options: {
                    rules: [{
                        required: true,
                        message: '类型必选!',
                    }]
                }
            },
            { label: '菜单地址', type: 'input', name: 'PageUrl'},
            { label: '描述', type: 'textarea', name: 'PermissionDescribe', options:{row: 2}},
            { label: '排序', type: 'inputNumber', name: 'PermissionSort', options:{setp: 1}},
        ]
    }

    fieldsEdit = () => {
        const item = this.state.item
        return [
            { label: '菜单名称', type: 'input', name: 'Name', items: item.PermissionDescribe,
                options: {
                    rules: [
                        { required: true, message: '权限名称必填!',}
                    ]
                }
            },
            {
                label: '类型',
                type: 'select',
                name: 'PermissionType',
                defaultValue: '后台',
                items: () => PermissionStatus,
                options: {
                    disabled: false,
                    initialValue:  keyToValue(PermissionStatus,(item.PermissionType || ''), 'value'),
                    rules: [{
                        required: true,
                        message: '权限类型必输!',
                    }]
                }
            },
            { label: '菜单地址', type: 'input', name: 'PageUrl'},
            { label: '描述', type: 'textarea', name: 'PermissionDescribe', options:{row: 2}},
            { label: '排序', type: 'inputNumber', name: 'PermissionSort', options:{setp:1}}]
    }

    render() {
        
        const columns = [
            { dataIndex: 'ArticleLogo', title: '文章Logo', width: 100,render: (text, record) =>  <img src={text} height="40" width="40" /> },
            { dataIndex: 'Title', title: '标题', width: 200,},
            // { dataIndex: 'ArticleTypeString', title: '类型', width: 100,},
            { dataIndex: 'ArticleOpenCount', title: '打开次数', width: 100,},
            { dataIndex: 'ArticleShareCount', title: '分享次数', width: 100,},
            { dataIndex: 'CreateUserName', title: '作者', width: 100,},
            { dataIndex: 'Status', title: '状态', width: 100,render: DeleteArticle => <a href="javascript:;" style={{color: (DeleteArticle == 1 ? 'red':'#40a9ff')}} >{DeleteArticle == 1 ? '已下架':'已上架'  }</a>,},

        ]
        return (
            <div id="wrap">
                <div className="tableBox">
                    <div style={{ paddingTop: 10 }}>
                        <Button type="primary" onClick={this.add} >添加</Button>
                        <Button type="primary" style={{marginLeft:'20px'}} onClick={this.addArticleLabel}>添加文章标签</Button>
                    </div>
                    <div style={{ paddingTop: 10 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            pagination={ true }
                            pageSize={10}
                            header={ columns}
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            action={row => [
                                { key: 'see', name: '预览', color: '#fa8c16', icon: 'read'},
                                { key: 'edit', name: '编辑', color: 'blue', icon: 'edit'},
                                { key: 'down', name: '下架', color: 'red', icon: 'eye-invisible',hidden:row.Status != 0},
                                { key: 'up', name: '上架', color: 'blue', icon: 'eye',hidden:row.Status != 1},
                            ]}
                            scroll={{y: 385 }}
                            total={this.state.Pages}
                            onChange={this.onPageChange}
                            currentPage={this.state.Page}
                        />
                    </div>
                </div>
                <ArticleModalForm
                    modalKey="add"
                    visible={this.state.modalShow}
                    title="添加"
                    fields={this.fields()}
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    okText="保存"
                    width="100%"
                    CategoryList={this.state.CategoryList}
                />
                <ArticleModalForm
                    modalKey="Edit"
                    visible={this.state.modalShowEdit}
                    title="编辑"
                    fields={this.fieldsEdit()}
                    onOk={this.onOkEdit}
                    onCancel={this.onCancel}
                    okText="保存"
                    data={this.state.item}
                    width="100%"
                    CategoryList={this.state.CategoryList}
                />

                <ArticleModalFormsee
                    modalKey="Edit"
                    visible={this.state.modalShowSee}
                    title="预览"
                    onOk={this.onOkEdit}
                    onCancel={this.onCancel}
                    okText="保存"
                    data={this.state.item}
                    width="400px"
                    CategoryList={this.state.CategoryList}
                />
                
                <FormtagModalForm
                    modalKey="Edit"
                    visible={this.state.tagmodalShowEdit}
                    title="添加文章标签"
                    fields={this.fieldsEdit()}
                    onOk={this.onOktagEdit}
                    onCancel={this.onCancel}
                    okText="保存"
                    data={this.state.item}
                    width="40%"
                />
            </div>
        )
    }
}



// WEBPACK FOOTER //
// ./src/routes/Article/Article/index.js


// WEBPACK FOOTER //
// src/routes/Article/Article/index.js